package model

import (
	"github.com/emicklei/go-restful/v3"
	"github.com/jinzhu/gorm"
	"strconv"
)

const (
	curPageDefault = 1
	pageSizeMin    = 10
	pageSizeMax    = 100
)

type PageRequest struct {
	CurPage  uint64 `json:"pageNum" description:"当前页"`
	PageSize uint64 `json:"pageSize" description:"页大小"`
}

func (p PageRequest) Response(count uint64) PageResponse {
	var totalPage uint64
	if count%p.PageSize != 0 {
		totalPage = count/p.PageSize + 1
	} else {
		totalPage = count / p.PageSize
	}
	return PageResponse{
		TotalCount: count,
		TotalPage:  totalPage,
		CurPage:    p.CurPage,
		PageSize:   p.PageSize,
	}
}

func (p *PageRequest) Reshape(count uint64) {
	var lastPage uint64
	if count%p.PageSize != 0 {
		lastPage = count/p.PageSize + 1
	} else {
		lastPage = count / p.PageSize
	}
	p.CurPage = lastPage
	return
}

func (p *PageRequest) PaginateGorm() func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		offset, limit := p.paginate()
		return db.Offset(offset).Limit(limit)
	}

}

func (p *PageRequest) PaginateCount(count uint64) (offset, limit uint64) {
	offset, limit = p.paginate()
	if offset > count {
		offset, limit = 0, 0
	} else {
		if offset+limit > count {
			limit = count - offset
		}
	}
	return
}

func GetPageRequest(request *restful.Request) (*PageRequest, error) {
	pageRequest := &PageRequest{
		CurPage:  curPageDefault,
		PageSize: pageSizeMin,
	}
	var err error
	if curPageStr := request.QueryParameter("pageNum"); len(curPageStr) > 0 {
		pageRequest.CurPage, err = strconv.ParseUint(curPageStr, 10, 64)
		if err != nil {
			return nil, err
		}
	}
	if pageSizeStr := request.QueryParameter("pageSize"); len(pageSizeStr) > 0 {
		pageRequest.PageSize, err = strconv.ParseUint(pageSizeStr, 10, 64)
		if err != nil {
			return nil, err
		}
	}

	return pageRequest, nil
}

type PageResponse struct {
	TotalCount uint64 `json:"total" description:"总记录数"`
	TotalPage  uint64 `json:"-" description:"总页数"`
	CurPage    uint64 `json:"pageNum" description:"当前页"`
	PageSize   uint64 `json:"pageSize" description:"页大小"`
}

func (p *PageRequest) paginate() (offset, limit uint64) {


	println("CurPage:",p.CurPage)
	println("PageSize:",p.PageSize)

	if p.CurPage == 0 {
		p.CurPage = curPageDefault
	}
	if p.PageSize > pageSizeMax {
		p.PageSize = pageSizeMax
	}
	if p.PageSize < pageSizeMin {
		p.PageSize = pageSizeMin
	}
	return (p.CurPage - 1) * p.PageSize, p.PageSize
}
